package com.ziyucoding.springboot.labs.lab4.concurrentdemo.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * CountDownLatch 示例2
 *
 * @author ziyucoding
 * @date 2022-10-27
 **/
@Slf4j
public class CountDownLatchExample2 {

    /**
     * 同时并发执行的线程数
     */
    private static int threadTotal = 200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch = new CountDownLatch(threadTotal);

        for (int i = 0; i < threadTotal; i++) {
            final int num = i;
            executorService.execute(() -> {
                try {
                    test(num);
                } catch (Exception e) {
                    log.error("发生异常", e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        countDownLatch.await(10, TimeUnit.MILLISECONDS);
        log.info("finish");
        executorService.shutdown();
    }

    /**
     * 测试
     *
     * @param num
     * @return void
     **/
    private static void test(int num) throws InterruptedException {
        Thread.sleep(100);
        log.info("threadNum:{}", num);
    }
}
